package com.atguigu.gmall.app.dim;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.app.function.DimSinkFunction;
import com.atguigu.gmall.app.function.TableProcessFunction;
import com.atguigu.gmall.util.MyKafkaUtils;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import com.ververica.cdc.connectors.mysql.table.StartupOptions;
import com.ververica.cdc.debezium.JsonDebeziumDeserializationSchema;
import lombok.extern.slf4j.Slf4j;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.util.Collector;

/**
 * 数据流：web/app -> nginx -> 业务服务器 -> Mysql(binlog) -> Maxwell -> Kafka(ODS) -> FlinkApp -> Phoenix
 * 程  序：Mock -> Mysql(binlog) -> Maxwell -> Kafka(ZK) -> DimApp(FlinkCDC/Mysql) -> Phoenix(HBase/ZK/HDFS)
 *
 * @author : ranzlupup
 * @since : 2023/5/31 22:10
 */
@Slf4j
public class DimApp {
    public static void main(String[] args) throws Exception {
        //! 1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);//? 生产环境中设置为Kafka主题的分区数

        // 1.1 开启checkpoint
        // env.enableCheckpointing(5 * 60000L, CheckpointingMode.EXACTLY_ONCE);
        // env.getCheckpointConfig().setCheckpointTimeout(10 * 60000L);
        // env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
        env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3, 5000L));

        // 1.2 设置状态后端
        // env.setStateBackend(new HashMapStateBackend());
        // env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/checkpoint/flink-realtime");
        // System.setProperty("HADOOP_USER_NAME", "atcper");

        //! 2.读取Kafka topic_db主题数据创建主流
        String topic = "FLINK_ODS_DB";
        String groupId = "FLINK_ODS_DB_GROUP";
        FlinkKafkaConsumer<String> flinkKafkaConsumerSource = MyKafkaUtils.getFlinkKafkaConsumer(topic, groupId);
        DataStreamSource<String> kafkaDStream = env.addSource(flinkKafkaConsumerSource);

        //! 3.过滤掉主流非JSON数据 和 保留新增、变化以及初始化数据
        SingleOutputStreamOperator<JSONObject> filterJsonObjDStream = kafkaDStream.flatMap(
                new FlatMapFunction<String, JSONObject>() {
                    @Override
                    public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                        try {
                            // 将数据转换为JSON格式
                            JSONObject jsonObject = JSONObject.parseObject(value);

                            // 获取数据中的操作类型字段
                            String type = jsonObject.getString("type");

                            // 保留新增、变化以及初始化数据 insert、update、bootstrap-insert
                            // if ("insert".equals(type) || "update".equals(type) || "bootstrap-insert".equals(type)) {
                            //     out.collect(jsonObject);
                            // }
                            switch (type) {
                                case "insert":
                                case "update":
                                case "bootstrap-insert":
                                    out.collect(jsonObject);
                            }
                        } catch (Exception e) {
                            System.out.println("发现脏数据: " + value);
                        }
                    }
                }
        );
        // filterJsonObjDStream.print();

        //! 4.使用Flink CDC读取MySQL配置信息表创建配置流
        // 4.1Flink CDC 读取配置表信息
        MySqlSource<String> mySqlSource = MySqlSource
                .<String>builder()
                .hostname("hadoop102")
                .port(3306)
                .databaseList("gmall-config")
                .tableList("gmall-config.table_process")
                .username("root")
                .password("123456")
                .deserializer(new JsonDebeziumDeserializationSchema())
                .startupOptions(StartupOptions.initial())
                .build();

        // 4.2封装为流
        DataStreamSource<String> mySqlDStreamSource = env.fromSource(mySqlSource, WatermarkStrategy.noWatermarks(), "MySqlSource");

        //! 5.将配置流处理为广播流
        MapStateDescriptor<String, com.atguigu.gmall.bean.TableProcess> tableProcessMapStateDescriptor = new MapStateDescriptor<>
                ("table-process-map-state", String.class, com.atguigu.gmall.bean.TableProcess.class);
        BroadcastStream<String> broadcastStream = mySqlDStreamSource.broadcast(tableProcessMapStateDescriptor);

        //! 6.连接主流与广播流
        BroadcastConnectedStream<JSONObject, String> connectedStream = filterJsonObjDStream.connect(broadcastStream);

        //! 7.处理连接流，根据配置信息处理主流数据
        SingleOutputStreamOperator<JSONObject> dimSingleOutputStreamOperator = connectedStream.process(new TableProcessFunction(tableProcessMapStateDescriptor));

        //! 8.将数据写出到Phoenix
        dimSingleOutputStreamOperator.print("将数据写出到Phoenix >>>>>>>>>");
        dimSingleOutputStreamOperator.addSink(new DimSinkFunction());

        //! 9.启动任务
        env.execute("DimApp");
    }
}
